package cn.edu.xaut.servlet;

import cn.edu.xaut.bean.UserBean;
import cn.edu.xaut.utils.JDBCUtils;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/findProcess")
public class FindProcess extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置编码格式
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        try {
            String message = request.getParameter("searchText");    // 获取文本框中的信息
            String sql = "select * from dbmis.tb_student ";
            if (message != null && !message.equals(""))
                sql += "where id = '" + message + "' or realname like '%"
                        + message + "%' or username like '%" + message + "%' or college like '%" + message + "%'";
            ResultSet rs = JDBCUtils.query(sql);    // 执行查询操作

            // 将查询到的数据存放到集合对象，然后转发到manage.jsp
            List<UserBean> userList = new ArrayList<>();
            while (rs.next()) {

                UserBean ub = new UserBean();

                ub.setId(rs.getInt("id"));
                ub.setUsername(rs.getString("username"));
                ub.setPassword(rs.getString("password"));
                ub.setRealname(rs.getString("realname"));
                ub.setTel(rs.getString("tel"));
                ub.setEmail(rs.getString("email"));
                ub.setCollege(rs.getString("college"));
                ub.setRegisterDate(rs.getDate("registertime").toString());

                userList.add(ub);
            }

            String json = JSON.toJSONString(userList);  //FASTJSON
            PrintWriter out = response.getWriter();
            out.println(json);



//            request.setAttribute("userlist", userList);
//            request.getRequestDispatcher("manage.jsp").forward(request, response);// 请求转发到manage.jsp
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release();    // 释放资源
        }
    }
}
